package com.cqust.wdm.emsboot.util;


import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

/**
 * @author
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public AjaxResult bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("发生业务异常！原因是：{}" , e.getErrorMsg());
        return AjaxResult.error(e.getErrorMsg(), e.getErrorMsg());
    }

    /**
     * 处理约束违例异常的业务异常
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public AjaxResult constraintViolationException(HttpServletRequest req, ConstraintViolationException e) {
        logger.error("发生业务异常！原因是：{}\n{}" , e.getLocalizedMessage(), req);
        return new AjaxResult(CommonEnum.BODY_NOT_MATCH, e.getLocalizedMessage());
    }

    /**
     * 处理约束违例异常的业务异常
     */
    @ExceptionHandler(value = UnauthorizedException.class)
    @ResponseBody
    public AjaxResult UnauthorizedException(HttpServletRequest req, UnauthorizedException e) {
        logger.error("发生业务异常！原因是：{}\n{}" , e.getLocalizedMessage(), req);
        return new AjaxResult(CommonEnum.SIGNATURE_NOT_MATCH, e.getLocalizedMessage());
    }

    /**
     * 处理约束违例异常的业务异常
     */
    @ExceptionHandler(value = DuplicateKeyException.class)
    @ResponseBody
    public AjaxResult constraintViolationException(HttpServletRequest req, DuplicateKeyException e) {
        logger.error("发生业务异常！原因是：{}\n{}" , e.getLocalizedMessage(), req);

        return new AjaxResult(CommonEnum.DataDuplication, e.getLocalizedMessage());
    }

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public AjaxResult exceptionHandler(HttpServletRequest req, NullPointerException e) {
        logger.error("发生空指针异常！原因是:" , e);
        return AjaxResult.error(CommonEnum.BODY_NOT_MATCH.getResultMsg());
    }


    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AjaxResult exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("未知异常！原因是:" , e);
        return AjaxResult.error(CommonEnum.INTERNAL_SERVER_ERROR.getResultMsg());
    }
}
